import React from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  WingBlank, WhiteSpace,
  InputItem, Button, Toast,
} from 'antd-mobile';
import { createForm } from 'rc-form';

// 个人资料中修改密码及确认修改新密码做的判断
const CheckPassword = ({ dispatch, form, ...rest }) => {
  const { getFieldProps, getFieldValue, getFieldError, validateFields } = form;
  const confirmPassword = () => validateFields((errors, value) => {
    if (errors) {
      const fieldNames = Object.keys(errors);
      if (fieldNames[0]) {
        return Toast.fail(getFieldError(fieldNames[0]));
      }
    }
    if (rest.action) {
      dispatch(rest.action(form));
      let pswd = getFieldProps("repswd").value;
      localStorage.removeItem('gyhlpass'+sessionStorage.getItem("hid"));
      localStorage.setItem('gyhlpass'+sessionStorage.getItem("hid"), pswd);
    }
  });

  const checkConfirm = (rule, value, callback) => {
    if (value && getFieldValue('pswd')) {
      validateFields(['repswd']);
    }

    callback();
  };

  const checkPassword = (rule, value, callback) => {
    if (value && value !== getFieldValue('pswd')) {
      Toast.fail('两次输入的密码不一致');
    } else {
      callback();
    }
  };

  return (
    <WingBlank size="md">
      <WhiteSpace />
      <InputItem
        {...getFieldProps('pswd', {
          validate: [{
            trigger: false,
            rules: [{
              required: true,
              message: '请输入新密码',
            }, {
              validator: checkConfirm,
            }]
          }],
        }) }
        type="password"
        placeholder="请输入新密码" />
      <InputItem
        {...getFieldProps('repswd', {
          validate: [{
            trigger: false,
            rules: [{
              required: true,
              message: '请确认新密码',
            }, {
              validator: checkPassword,
            }],
          }],
        }) }
        type="password"
        placeholder="请确认新密码" />
      <WhiteSpace />
      <Button type="primary" onClick={confirmPassword}>
        {rest.buttonText || '确定'}
      </Button>
      <WhiteSpace />
    </WingBlank>
  );
};

export default connect()(createForm()(CheckPassword));
